<template>
	<view class="days-container">
		<!-- 日期选择器 -->
		<view class="calendar-section">
			<view class="calendar-header">
				<view class="month-selector">
					<text class="arrow" @tap="changeMonth(-1)">＜</text>
					<picker mode="date" :value="selectedDate" :start="startYear + '-01-01'" :end="endYear + '-12-31'" @change="onDatePickerChange">
						<text class="current-month">{{year}}年{{month}}月</text>
					</picker>
					<text class="arrow" @tap="changeMonth(1)">＞</text>
				</view>
				<text class="fold-btn" @tap="toggleCalendar">^</text>
			</view>
			
			<!-- 添加日期选择器 -->
			<picker-view
				v-if="showDatePicker"
				class="date-picker"
				:indicator-style="'height: 50px;'"
				:value="pickerValue"
				@change="onDatePickerChange"
			>
				<picker-view-column>
					<view class="picker-item" v-for="year in years" :key="year">
						{{year}}年
					</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="month in months" :key="month">
						{{month}}月
					</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="day in days" :key="day">
						{{day}}日
					</view>
				</picker-view-column>
			</picker-view>
			
			<view class="calendar-body">
				<!-- 星期表头 -->
				<view class="weekday-row">
					<text class="weekday" v-for="day in ['一','二','三','四','五','六','日']" :key="day"
						:class="{'weekend': day === '六' || day === '日'}">{{day}}</text>
				</view>
				
				<!-- 日期网格 -->
				<view class="date-grid">
					<view class="date-item" 
						v-for="(date, index) in dateList" 
						:key="index"
						:class="{
							'selected': isSelectedDate(date),
							'today': isToday(date),
							'weekend': isWeekend(date),
							'other-month': date.month !== month
						}"
						@tap="selectDate(date)"
					>
						<text class="date-number">{{date.day}}</text>
						<text class="lunar-date" v-if="date.lunar">{{date.lunar}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 预约记录列表 -->
		<scroll-view 
			class="booking-section"
			scroll-y="true"
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onPullDownRefresh"
			:scroll-anchoring="true"
			:enhanced="true"
			:bounces="false"
		>
			<view class="section-title">
				<text>{{selectedDate || '今日'}}预约记录</text>
				<text class="booking-count" v-if="bookingList && bookingList.length">
					({{bookingList.length}}条)
				</text>
			</view>
			
			<!-- 无预约记录时显示 -->
			<view class="empty-tip" v-if="!bookingList || bookingList.length === 0">
				<image 
					src="/static/images/index_page.png" 
					mode="aspectFit" 
					class="empty-image"
					lazy-load
				></image>
				<text>当前日期暂无预约记录</text>
			</view>
			
			<!-- 预约记录列表 -->
			<view class="booking-list" v-else>
				<view class="booking-item" 
					v-for="(item, index) in bookingList" 
					:key="index"
					@tap="showBookingDetail(item)"
					>
					<view class="booking-header">
						<text class="booking-time">{{item.timeSlot}}</text>
						<text :class="['booking-type', `type-${item.type}`]">{{item.typeText}}</text>
					</view>
					<view class="booking-content">
						<view class="service-name">{{item.serviceName}}</view>
					</view>
					<view class="booking-status" :class="item.status">
						{{item.statusText}}
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import config from '@/config/config.js'
export default {
	data() {
		return {
			year: new Date().getFullYear(),
			month: new Date().getMonth() + 1,
			selectedDate: new Date().toISOString().split('T')[0],
			dateList: [],
			isCalendarExpanded: true,
			isRefreshing: false,
			bookingList: [],
			showDatePicker: false,
			pickerValue: [],
			startYear: 2020,
			endYear: 2025,
			years: [],
			months: Array.from({length: 12}, (_, i) => i + 1),
			days: [],
			pageNo: 1,
			pageSize: 10,
			total: 0,
			loading: false,
			hasMore: true
		}
	},
	methods: {
		// 生成日历数据
		generateCalendar() {
			const firstDay = new Date(this.year, this.month - 1, 1)
			const lastDay = new Date(this.year, this.month, 0)
			const dateList = []
			
			// 获取当月第一天是星期几（0是星期日）
			let firstDayWeek = firstDay.getDay() || 7
			
			// 补充上月日期
			for (let i = firstDayWeek - 1; i > 0; i--) {
				const date = new Date(this.year, this.month - 2, -i + 2)
				dateList.push({
					year: date.getFullYear(),
					month: date.getMonth() + 1,
					day: date.getDate(),
					lunar: this.getLunarDate(date) // 添加农历日期
				})
			}
			
			// 当月日期
			for (let i = 1; i <= lastDay.getDate(); i++) {
				const date = new Date(this.year, this.month - 1, i)
				dateList.push({
					year: this.year,
					month: this.month,
					day: i,
					lunar: this.getLunarDate(date)
				})
			}
			
			// 补充下月日期
			const remainingDays = 42 - dateList.length // 保持6行
			for (let i = 1; i <= remainingDays; i++) {
				const date = new Date(this.year, this.month, i)
				dateList.push({
					year: date.getFullYear(),
					month: date.getMonth() + 1,
					day: date.getDate(),
					lunar: this.getLunarDate(date)
				})
			}
			
			this.dateList = dateList
		},
		
		// 切换月份
		changeMonth(delta) {
			let newMonth = this.month + delta
			let newYear = this.year
			
			if (newMonth > 12) {
				newMonth = 1
				newYear++
			} else if (newMonth < 1) {
				newMonth = 12
				newYear--
			}
			
			if (newYear >= this.startYear && newYear <= this.endYear) {
				this.year = newYear
				this.month = newMonth
				this.updateDays()
				this.generateCalendar()
			}
		},
		
		// 选择日期
		async selectDate(date) {
			this.selectedDate = `${date.year}-${String(date.month).padStart(2, '0')}-${String(date.day).padStart(2, '0')}`
			await this.getBookingsByDate()
			
			// 预加载下一页数据
			if (this.hasMore) {
				this.preloadNextPage()
			}
		},
		
		// 判断是否是选中日期
		isSelectedDate(date) {
			return this.selectedDate === `${date.year}-${String(date.month).padStart(2, '0')}-${String(date.day).padStart(2, '0')}`
		},
		
		// 判断是否是今天
		isToday(date) {
			const today = new Date()
			return date.year === today.getFullYear() &&
				date.month === today.getMonth() + 1 &&
				date.day === today.getDate()
		},
		
		// 判断是否是周末
		isWeekend(date) {
			const d = new Date(date.year, date.month - 1, date.day)
			const day = d.getDay()
			return day === 0 || day === 6
		},
		
		// 获取农历日期（示例实现，实际需要农历转换库）
		getLunarDate(date) {
			// 这里应该使用农历转换库
			// 示例仅返回节日
			const festivals = {
				'11-7': '立冬',
				'11-25': '感恩节'
			}
			const key = `${date.getMonth() + 1}-${date.getDate()}`
			return festivals[key] || ''
		},
		
		// 展开/收起日历
		toggleCalendar() {
			this.isCalendarExpanded = !this.isCalendarExpanded
		},
		
		async onPullDownRefresh() {
			this.isRefreshing = true
			await this.getBookingsByDate()
		},
		
		async loadMore() {
			if (!this.hasMore || this.loading) return
			
			this.pageNo++
			await this.getBookingsByDate(true)
		},
		
		showBookingDetail(item) {
			uni.showModal({
				title: '预约详情',
				content: `服务项目：${item.serviceName}\n预约时间：${item.timeSlot}\n预约来源：${item.typeText}\n当前状态：${item.statusText}`,
				showCancel: false
			})
		},
		async getBookingsByDate(isLoadMore = false) {
			if (this.loading) return
			this.loading = true
			
			try {
				if (!isLoadMore) {
					this.pageNo = 1
					this.hasMore = true
				}
				
				const res = await this.$http.post(config.api.appointment.queryCalendarApoints, {
					apointTime: this.selectedDate,
					pageNo: this.pageNo,
					pageSize: this.pageSize
				})
				
				console.log('获取预约记录响应:', res.data)
				
				if (res.data.code === 200 || res.data.code === 201) {
					const list = (res.data.data || []).map(item => ({
						timeSlot: item.timeSolt,
						type: item.type,
						typeText: this.getTypeText(item.type),
						serviceName: item.serviceName,
						status: item.status,
						statusText: item.statusText || this.getStatusText(item.status),
						customerName: item.customerName,
						customerPhone: item.customerPhone
					}))
					
					if (!isLoadMore) {
						this.bookingList = list
					} else {
						this.bookingList = [...this.bookingList, ...list]
					}
					
					// 更新总数和是否还有更多
					this.total = res.data.total || 0
					this.hasMore = this.bookingList.length < this.total
				} else {
					throw new Error(res.data.message || '获取预约记录失败')
				}
			} catch (error) {
				console.error('获取预约记录失败:', error)
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				if (this.isRefreshing) {
					this.isRefreshing = false
				}
			}
		},
		
		// 添加类型转换方法
		getTypeText(type) {
			const typeMap = {
				'1': '美团预约',
				'2': '抖音预约',
				'6': '会员预约'
				// 添加其他类型映射
			}
			return typeMap[type] || '普通预约'
		},
		
		// 添加状态转换方法
		getStatusText(status) {
			const statusMap = {
				'0': '待服务',
				'1': '已完成',
				'2': '已取消'
				// 添加其他状态映射
			}
			return statusMap[status] || '待服务'
		},
		
		// 更新日期数组
		updateDays() {
			const daysInMonth = new Date(this.year, this.month, 0).getDate()
			this.days = Array.from({length: daysInMonth}, (_, i) => i + 1)
		},
		
		// 日期选择器变化事件
		onDatePickerChange(e) {
			const dateStr = e.detail.value // 格式：YYYY-MM-DD
			const [year, month, day] = dateStr.split('-').map(Number)
			
			this.year = year
			this.month = month
			this.generateCalendar()
			this.selectDate({
				year,
				month,
				day
			})
		},
		
		// 添加图片缓存方法
		async cacheImage(url) {
			try {
				// 先检查本地是否已缓存
				const savedPath = uni.getStorageSync(`img_cache_${url}`)
				if (savedPath) {
					return savedPath
				}
				
				// 下载图片
				const downloadRes = await uni.downloadFile({
					url: url
				})
				
				if (downloadRes.statusCode === 200) {
					// 保存图片路径到本地存储
					uni.setStorageSync(`img_cache_${url}`, downloadRes.tempFilePath)
					return downloadRes.tempFilePath
				}
				
				return url
			} catch (err) {
				console.error('图片缓存失败:', err)
				return url
			}
		},
		
		// 添加预加载方法
		async preloadNextPage() {
			const nextPage = this.pageNo + 1
			try {
				const res = await this.$http.post(config.api.appointment.queryCalendarApoints, {
					apointTime: this.selectedDate,
					pageNo: nextPage,
					pageSize: this.pageSize
				})
				
				if (res.data.code === 200 || res.data.code === 201) {
					// 预加载图片
					const list = res.data.data || []
					list.forEach(item => {
						if (item.image) {
							this.cacheImage(item.image)
						}
					})
				}
			} catch (err) {
				console.error('预加载失败:', err)
			}
		}
	},
	mounted() {
		this.updateDays()
		this.generateCalendar()
		this.getBookingsByDate()
	},
	onLoad() {
		this.updateDays()
		this.getBookingsByDate()
	}
}
</script>

<style>
.days-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f8f8f8;
}

.calendar-section {
	background-color: #fff;
	border-radius: 12rpx;
	margin: 20rpx;
	overflow: hidden;
}

.calendar-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #eee;
}

.month-selector {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.current-month {
	font-size: 32rpx;
	font-weight: bold;
	padding: 10rpx 20rpx;
}

.current-month:active {
	opacity: 0.7;
}

.arrow {
	padding: 10rpx 20rpx;
	color: #666;
}

.fold-btn {
	color: #666;
	transform: rotate(180deg);
}

.weekday-row {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
}

.weekday {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
}

.weekend {
	color: #ff6b81;
}

.date-grid {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	padding: 10rpx;
}

.date-item {
	aspect-ratio: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 10rpx;
	position: relative;
}

.date-number {
	font-size: 28rpx;
	line-height: 1.2;
}

.lunar-date {
	font-size: 20rpx;
	color: #999;
	margin-top: 4rpx;
}

.selected {
	background-color: #000;
	color: #fff;
	border-radius: 8rpx;
}

.selected .lunar-date {
	color: rgba(255, 255, 255, 0.8);
}

.today {
	color: #ff6b81;
}

.other-month {
	color: #ccc;
}

.other-month .lunar-date {
	color: #eee;
}

.booking-section {
	flex: 1;
	padding: 0 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	padding: 20rpx 10rpx;
	color: #333;
}

.booking-count {
	font-size: 24rpx;
	color: #999;
	margin-left: 10rpx;
}

.empty-tip {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 60rpx 0;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 20rpx;
}

.booking-list {
	padding: 10rpx 0;
}

.booking-item {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.booking-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.booking-time {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.booking-type {
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
}

.booking-type.type-1 {
	background-color: #FFE4E1;
	color: #FF6B81;
}

.booking-type.type-2 {
	background-color: #E8F4FF;
	color: #3498db;
}

.booking-type.type-6 {
	background-color: #E6FFE4;
	color: #2ecc71;
}

.service-name {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 8rpx;
}

.booking-status {
	text-align: right;
	font-size: 24rpx;
	margin-top: 10rpx;
}

.booking-status.pending {
	color: #f39c12;
}

.booking-status.completed {
	color: #2ecc71;
}

.booking-status.cancelled {
	color: #95a5a6;
}

.date-picker {
	width: 100%;
	height: 400rpx;
	background-color: #fff;
	position: absolute;
	top: 100%;
	left: 0;
	z-index: 100;
}

.picker-item {
	line-height: 50px;
	text-align: center;
}

.current {
	color: #ff6b81;
}
</style>

